package org.demo.rc.client;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

/**
 * 图像处理类
 * @author 
 *
 */
public class ImageConsumeTask implements Runnable{
	private MonitorClient parent;
	private JImagePanel imgPanel;
	private int wait_timeout = 2000;
	/**
	 * 构造函数
	 * @param parent
	 */
	public ImageConsumeTask(MonitorClient parent,JImagePanel imgPanel){
		this.parent = parent;
		this.imgPanel = imgPanel;
		wait_timeout = Integer.parseInt(
				               parent.getProperties()
				              .getProperty("wait_timeout", "2000"));
	}
	/**
	 * 执行任务
	 */
	public void run() {
		while(!parent.isClosed()){
			try {
				byte[] data = parent.getImgQueue().poll();
				if (data == null){
					// 没有任务时等两秒
					if (wait_timeout > 0){
					    Thread.sleep(wait_timeout);
					}
					continue;
				}
				imgConsume(data);
			} catch(Exception e){
				System.out.println("img handler:> " + e.getMessage());
			}
		}
		
	}
	/**
	 * 图像处理
	 * @param data
	 */
	public void imgConsume(byte[] data){
		// 
		try {
			ByteArrayInputStream in = new ByteArrayInputStream(data);
			JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
			BufferedImage image = decoder.decodeAsBufferedImage();
			imgPanel.setImage(image);
			imgPanel.updateUI();
		} catch(Exception e){
			System.out.println("imgConsume:> " + e.getMessage());
		}
	}
}
